package jerry.html.data.accessors;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;

import jerry.html.data.DataType;

/**
 * 
 * Abstract data accessor class for handling database
 * 
 * 
 * @author (h0t@_G0|i
 * 
 */
public abstract class DataAccessor {
	
	protected HashMap<String, DataType> data; 
	@SuppressWarnings("unchecked")
	public synchronized DataType getData(String identity) throws Exception{
		FileInputStream stream = new FileInputStream(databaseFile);
		ObjectInputStream objInStream = new ObjectInputStream(stream);
		data = (HashMap<String, DataType>) objInStream.readObject();
		objInStream.close();
		return data.get(identity);
	}
	@SuppressWarnings("unchecked")
	public synchronized void updateData(DataType toUpdate) throws Exception {
		FileInputStream stream = new FileInputStream(databaseFile);
		ObjectInputStream objInStream = new ObjectInputStream(stream);
		data = (HashMap<String, DataType>) objInStream.readObject();
		objInStream.close();
		data.put(toUpdate.getIdentity(), toUpdate);
		ObjectOutputStream oStream = new ObjectOutputStream(new FileOutputStream(databaseFile));
		oStream.writeObject(data);
		oStream.flush();
		oStream.close();
	}
	
	public DataAccessor(String utDBDir, String dbName) {
		this.utDBDir = utDBDir;
		databaseFile = new File(utDBDir + File.separatorChar + dbName);
		if(!databaseFile.exists()) { 
			try {
				databaseFile.createNewFile();
				ObjectOutputStream oStream = new ObjectOutputStream(new FileOutputStream(databaseFile));
				oStream.writeObject(new HashMap<String, DataType>());
				oStream.flush();
				oStream.close();
			} catch (IOException e) {
				System.err.println("Couldn't create file named" + databaseFile.getAbsolutePath());
			}
		}
	}
	protected final String utDBDir;
	protected final File databaseFile;
}
